﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using AliNetpad.Data;
using System.Text;
using System.Xml;
using System.IO;
using System.Net;
using System.Web.Security;
using Fan.Dongping.Ali.DataAccess;
using Fan.Dongping.Common.DBMeta;

namespace Fan.Dongping.Ali.Notepad.Web.User
{
    public partial class ValidateUser : System.Web.UI.Page
    {
        //用于页面显示，具体应用可以不处理

        public string timestamps;
        public string sipsign;
        public string appkey;
        public string apiname = "alisoft.validateUser";//接口调用名称
        public string messages;
        string appUserId;
        //end
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpRequest request = HttpContext.Current.Request;
            //在软件应用中心跳转到ISV应用时的URL参数中取得,user_id、app_instance_id和token
            appUserId = request.Params["user_id"];
            string appInstanceId = request.Params["app_instance_id"];
            string appId = request.Params["app_id"]; //软件注册时获得
            string token = request.Params["token"]; //每次点击生成不一样的token，并只有10秒钟有效

            Session["user_id"] = appUserId;
            Session["app_instance_id"] = appInstanceId;
            Session["app_id"] = appId;

            if (appInstanceId == null)
            {
                messages = "免登录失败，此为非法请求";
            }
            else
            {
                System.DateTime timestamp = System.DateTime.Now;//时间获得当前系统时间
                appkey = appId;//接口调用需要的参数
                timestamps = timestamp.ToString();
                //http://localhost:3624/default.aspx?user_id=20766253&app_id=24322&app_instance_id=USER87C58F9135C395DE4EEEB257F0AAC4FE&token=849B5B9D42467E3867017336B894F1B60A982505B2A3F78303D188993F29621D895CF76E52E0ADE18C58BCB21BDCDDB4&target=
                //sip_sign签名字段的生成，将CERT CODE和所有接口要传的参数进行组合，再将组装好的字符串进行md5加密后转成16进制后得到一个32位的密文
                SortedList mySL = new SortedList();
                mySL.Add("appId", appId);
                //mySL.Add("", "401ae2d0200611de9af2f8a7cfb13186"); 
                mySL.Add("appInstanceId", appInstanceId);
                mySL.Add("token", token);
                mySL.Add("userId", appUserId);
                mySL.Add("sip_appkey", appId);
                mySL.Add("sip_timestamp", timestamp);
                mySL.Add("sip_apiname", apiname);
                sipsign = Signature.DoSignature(mySL);

                //sip_sign生成END


                //系统级参数拼装，包括sip_appkey、sip_apiname、sip_timestamp和sip_sign，sip_apiname是接口名这里举validateUser为例
                string SIPdate = "sip_appkey=" + appId + "&sip_apiname=" + apiname + "&sip_timestamp=" + timestamp + "&sip_sign=" + sipsign;
                //接口级参数拼装
                string apidate = "&userId=" + appUserId + "&appId=" + appId + "&appInstanceId=" + appInstanceId + "&token=" + token;

                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] postdata = encoding.GetBytes(SIPdate + apidate);//所有要传参数拼装
                // Prepare web request...
                //目前阿里软件的服务集成平台（SIP）的接口
                //测试地址是：http://sipdev.alisoft.com/sip/rest，软件测试开发调用
                //正式环境地址是：http://sip.alisoft.com/sip/rest,软件发布上线后调用。
                //这里使用正式环境URL,测试环境使用http://sipdev.alisoft.com/sip/rest。

                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://sipdev.alisoft.com/sip/rest");
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                myRequest.ContentLength = postdata.Length;
                Stream newStream = myRequest.GetRequestStream();
                // Send the data.
                newStream.Write(postdata, 0, postdata.Length);
                newStream.Close();
                // Get response

                //以下内容为接口返回结果解析
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                string status = myResponse.Headers.Get("sip_status");//获得接口返回状态码

                if (status != null)
                {
                    //Sip返回结果为成功的情况
                    if ("9999".Equals(status))
                    {
                        StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                        string content = reader.ReadToEnd();
                        //解析接口返回值，这里选用XML格式的解析，接口默认返回是XML格式
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.LoadXml(content);
                        XmlNode xn = xmlDoc.SelectSingleNode("String");
                        XmlElement xe = (XmlElement)xn;
                        string result = xe.InnerText;
                        if (result == "0")
                        {
                            //使用者
                            validatePass();

                        }
                        else if (result == "1")
                        {
                            //订购者
                            validatePass();
                        }
                        else
                        {
                            setMessage(result);//用于页面显示
                        }
                    }
                    //SIP返回错误信息解析,此处为了说明各返回值，ISV可不用处理这么详细
                    else
                    {
                        setMessage(status);//用于页面显示
                    }
                }
            }

        }
        ///<summary>
        ///根据传入的值，返回相应的接口返回结果
        ///
        ///</summary>
        private void setMessage(String result)
        {
            switch (Int32.Parse(result))
            {
                case 1: messages = "您是订购者，免登录成功"; break; //订购者和使用者是有权使用的用户
                case 0: messages = "您是使用者，免登录成功"; break;
                case -1: messages = "免登录失败，错误信息：尚未订购该应用"; break;
                case -2: messages = "免登录失败，错误信息：非法用户"; break;
                case -3: messages = "免登录失败，错误信息：没有订购"; break;
                case -4: messages = "免登录失败，错误信息：订阅了多个，不明确"; break;
                case 1001: messages = "免登录失败，错误信息：签名无效"; break;
                case 1002: messages = "免登录失败，错误信息：请求已过期"; break;
                case 1004: messages = "免登录失败，错误信息：需要绑定用户"; break;
                case 1005: messages = "免登录失败，错误信息：需要提供appid"; break;
                case 1006: messages = "免登录失败，错误信息：需要提供服务名"; break;
                case 1007: messages = "免登录失败，错误信息：需要提供签名"; break;
                case 1008: messages = "免登录失败，错误信息：需要提供时间戳"; break;
                case 1010: messages = "免登录失败，错误信息：无权访问服务"; break;
                case 1011: messages = "免登录失败，错误信息：服务不存在"; break;
                case 1012: messages = "免登录失败，错误信息：需要提供SessionId"; break;
                case 1013: messages = "免登录失败，错误信息：需要提供用户名"; break;
                case 1014: messages = "免登录失败，错误信息：回调服务不存在"; break;
                case 1015: messages = "免登录失败，错误信息：AppKey不存在"; break;
                case 1016: messages = "免登录失败，错误信息：服务次数超过限制"; break;
                case 1017: messages = "免登录失败，错误信息：服务请求过于频繁"; break;
                case 1018: messages = "免登录失败，错误信息：登录请求URL过长"; break;
                case 1019: messages = "免登录失败，错误信息：ISP请求IP非法"; break;
                case 1020: messages = "免登录失败，错误信息：请求参数值长度溢出"; break;
                case 1021: messages = "免登录失败，错误信息：isp处理请求失败"; break;
                default: messages = "免登录失败，错误信息：未知异常"; break;
            }
        }

        private void validatePass()
        {
            //this.Trace.Write(this.User.Identity.Name);
            //如果用户验证正确者转到index.aspx
            //否则显示错误信息
            //UserDA.UpdateLastLogin(appUserId);

            //try
            //{
            //    Dictionary<string, OnlineUser> dic = (Dictionary<string, OnlineUser>)Application["OnlineList"];
            //    dic[Session.SessionID].UserName = this.txtUserName.Text;
            //}
            //catch { }

            //LogDA.AddLog(LogMeta.InformationType, string.Format("Logined: {0} ,IP: {1}", appUserId, Request.UserHostAddress));

            //
            //Collection<string> groupList = PermissionBiz.GetPermissionByUser(txtUserName.Text);

            string groups = string.Empty;
            //string I = string.Empty;
            //foreach (string s in groupList)
            //{
            //    groups += I;
            //    groups += s;
            //    I = "|";
            //}

            //Create the authentication ticket
            FormsAuthenticationTicket authTicket;

            authTicket = new FormsAuthenticationTicket(1, appUserId, DateTime.Now, DateTime.Now.AddMinutes(120), false, groups);

            // Now encrypt the ticket.
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            // Create a cookie and add the encrypted ticket to the 
            // cookie as data.
            HttpCookie authCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket);
            authCookie.Expires = authTicket.Expiration;
            authCookie.Path = System.Web.Security.FormsAuthentication.FormsCookiePath;

            // Add the cookie to the outgoing cookies collection. 
            Response.Cookies.Add(authCookie);

            // Redirect the user to the originally requested page
            string url = FormsAuthentication.GetRedirectUrl(appUserId, false);
            if (
                url.Contains(@"/default.aspx")
                || url.Contains(@"/Default.aspx")
                || url.Equals(@"/Default.htm", StringComparison.InvariantCultureIgnoreCase)
                || url.Equals(@"/Default.aspx", StringComparison.InvariantCultureIgnoreCase)
                || url.Equals(@"/Title.aspx", StringComparison.InvariantCultureIgnoreCase)
                || url.Equals(@"Webspms/Default.aspx", StringComparison.InvariantCultureIgnoreCase)
                )
            {
                //如果从首页页面，则转到loginPass页
                url = @"comm";
            }
            Response.Redirect(url);

        }
    }
}
